package cn.dt70.controller;

import cn.dt70.pojo.AqbBankcard;
import cn.dt70.pojo.AqbBorrow;
import cn.dt70.pojo.AqbProject;
import cn.dt70.pojo.AqbUser;
import cn.dt70.service.AqbBankcardService;
import cn.dt70.service.AqbBorrowService;
import cn.dt70.service.AqbProjectService;
import cn.dt70.utils.Constants;
import cn.dt70.utils.PageSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/borrow")
public class BorrowController {

    @Resource
    private AqbProjectService aqbProjectService;
    @Resource
    private AqbBorrowService aqbBorrowService;
    @Resource
    private AqbBankcardService aqbBankcardService;

    @RequestMapping("/list")
    public String borrowList(PageSupport ps, HttpSession session, Model model, String status) {
        double userAmountSum = 0;
        double userInterestSum = 0;
        double userPayAmount = 0;
        double userPayInterest = 0;
        int status1 = 0;
        int status2 = 0;
        AqbUser aqbUser = (AqbUser) session.getAttribute(Constants.USER_SESSION);
        if ("".equals(status) || status == null || "0".equals(status)) {
            status1 = 3;
            status2 = 4;
        }
        if ("3".equals(status)) {
            status1 = 3;
            status2 = 0;
        }
        if ("4".equals(status)) {
            status1 = 4;
            status2 = 0;
        }

        ps.setTotalCount(aqbProjectService.findTotalCountOfProjectList(aqbUser.getUserId(), 0, status1, status2));
        List<AqbProject> aqbProjects = aqbProjectService.findReturnProjectList(aqbUser.getUserId(), status1, status2, ps);
        for (AqbProject project : aqbProjects) {
            userAmountSum += project.getProAmount();
            userInterestSum += project.getPayableInterest().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            userPayAmount += project.getPayMoneySum().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            userPayInterest += project.getPayInterestSum().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        model.addAttribute("userAmountSum", userAmountSum);
        model.addAttribute("userInterestSum", userInterestSum);
        model.addAttribute("userPayAmount", userPayAmount);
        model.addAttribute("userPayInterest", userPayInterest);
        model.addAttribute("aqbProjects", aqbProjects);
        model.addAttribute("ps", ps);
        model.addAttribute("status", status);
        return "usercenter-investcontrol-borrowmoney";
    }

    @RequestMapping("/info")
    public String borrowInfo(PageSupport ps, HttpSession session, String proId, Model model, String Msg) {
        String userId = ((AqbUser) session.getAttribute(Constants.USER_SESSION)).getUserId().toString();
        List<AqbBorrow> aqbBorrows = aqbBorrowService.getAllByUidAndProId(ps, proId, userId);
        int row = aqbBorrowService.getCount(proId, userId);
        AqbProject aqbProject = aqbProjectService.findOneProject(Integer.parseInt(proId), null);
        double principal = aqbProject.getProAmount() - aqbProject.getPayMoneySum().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        double interest = aqbProject.getRate().setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue() / 12;
        double repayment = 0.00;
        int periods = 0;
        if (aqbProject.getReturnType() == 1) {
            repayment = new BigDecimal(principal * interest).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            periods = aqbProject.getPeriod() - row;
            if (periods != 0) {
                repayment += new BigDecimal(principal / periods).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            } else {
                repayment = 0.00;
            }
        } else if (aqbProject.getReturnType() == 2) {
            repayment = new BigDecimal(principal * interest).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            periods = aqbProject.getPeriod() - aqbBorrows.size();
            if (periods == 1) {
                repayment += principal;
            }
        }
        model.addAttribute("repayment", repayment);
        model.addAttribute("aqbBorrows", aqbBorrows);
        model.addAttribute("Msg", Msg);
        model.addAttribute("ps", ps);
        model.addAttribute("proId", proId);
        return "usercenter-investcontrol-paymoney";
    }

    @RequestMapping("/pay")
    public String PayMoney(double payMoney, HttpSession session, Model model, String proId) {
        String userId = ((AqbUser) session.getAttribute(Constants.USER_SESSION)).getUserId().toString();
        if (isEnough(payMoney, userId)) {
            //查出该项目和已还款期数和该项目最后一条还款记录
            AqbProject aqbProject = aqbProjectService.findOneProject(Integer.parseInt(proId), null);
            int row = aqbBorrowService.getCount(proId, userId);
            AqbBorrow aqbBorrow = aqbBorrowService.findBorrowOne(userId, proId);
            AqbBankcard aqbBankcard = aqbBankcardService.findByUserId(userId);
            Date borDate = null;
            if(aqbBorrow == null){
                borDate = new Date();
            }else{
                borDate = aqbBorrow.getPayDate();
            }
            //得到满标日期，该项目还款记录最后一期日期和当前的日期
            Date fullDate = aqbProject.getFullDate();
            Date today = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(fullDate);
            cal.add(Calendar.MONTH, row);
            Date lastDate = cal.getTime();
            //最后一条还款记录的付款日期小于最后一期的日期并且当前日期也小于最后一期日期，说明是同一期内的还款
            if (borDate.getTime() <= lastDate.getTime() && today.getTime() <= lastDate.getTime()) {
                double principal = aqbProject.getProAmount() - aqbProject.getPayMoneySum().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                double interest = aqbProject.getRate().setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue() / 12;
                double payInterest = new BigDecimal(principal * interest).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                if(aqbBorrow.getPayInterest() < payInterest && payMoney <= (payInterest - aqbBorrow.getPayInterest())){
                    aqbBorrowService.modifyBorrowInterest(payMoney + aqbBorrow.getPayInterest(),aqbBorrow.getBkId().toString());
                    aqbProjectService.modifyPayInterestSum(aqbProject.getPayInterestSum().add(new BigDecimal(payMoney)),Integer.parseInt(proId));
                }else if(aqbBorrow.getPayInterest() < payInterest && payMoney > (payInterest - aqbBorrow.getPayInterest())){
                    aqbBorrowService.modifyBorrowInterest(payInterest,aqbBorrow.getBkId().toString());
                    aqbBorrowService.modifyBorrow(payMoney - payInterest,aqbBorrow.getObligation() - (payMoney - payInterest),aqbBorrow.getBkId().toString());
                    aqbProjectService.modifyPayInterestSum(aqbProject.getPayInterestSum().add(new BigDecimal(payInterest - aqbBorrow.getPayInterest())),Integer.parseInt(proId));
                    aqbProjectService.modifyPayMoneySum(aqbProject.getPayMoneySum().add(new BigDecimal(payMoney - (payInterest - aqbBorrow.getPayInterest()))),Integer.parseInt(proId));
                }else if(aqbBorrow.getPayInterest() >= payInterest){
                    aqbBorrowService.modifyBorrow(payMoney,aqbBorrow.getObligation() - payMoney,aqbBorrow.getBkId().toString());
                    aqbProjectService.modifyPayMoneySum(aqbProject.getPayMoneySum().add(new BigDecimal(payMoney)),Integer.parseInt(proId));
                }
                aqbBankcardService.modifyBankMoney(userId,aqbBankcard.getMoney() - payMoney);

                //最后一条还款记录的付款日期小于最后一期的日期并且当前日期大于最后一期日期，说明是新的一期还款
            } else if ((borDate.getTime() <= lastDate.getTime() && today.getTime() > lastDate.getTime()) || (borDate.getTime() >= lastDate.getTime() && today.getTime() > lastDate.getTime())) {
                double principal = aqbProject.getProAmount() - aqbProject.getPayMoneySum().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                double interest = aqbProject.getRate().setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue() / 12;
                AqbBorrow aqbBorrowOne = new AqbBorrow();
                aqbBorrowOne.setUsesrId(Integer.parseInt(userId));
                aqbBorrowOne.setBorrowId(Integer.parseInt(proId));
                double payInterest = new BigDecimal(principal * interest).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                if(payMoney <= (principal + payInterest)){
                    if(payMoney >= payInterest){
                        aqbBorrowOne.setPayInterest(payInterest);
                        aqbBorrowOne.setPayMoney(payMoney - payInterest);
                        aqbBorrowOne.setObligation(principal - (payMoney - payInterest));
                    }else{
                        aqbBorrowOne.setPayInterest(payMoney);
                        aqbBorrowOne.setPayMoney(0.00);
                        aqbBorrowOne.setObligation(principal);
                    }
                    boolean flag = aqbBorrowService.addBorrowOne(aqbBorrowOne);
                    if (flag) {
                        if(payMoney >= payInterest){
                            aqbProjectService.modifyPayMoneySum(aqbProject.getPayMoneySum().add(new BigDecimal(payMoney - payInterest)),Integer.parseInt(proId));
                            aqbProjectService.modifyPayInterestSum(aqbProject.getPayInterestSum().add(new BigDecimal(payInterest)),Integer.parseInt(proId));
                        }else{
                            aqbProjectService.modifyPayInterestSum(aqbProject.getPayInterestSum().add(new BigDecimal(payMoney)),Integer.parseInt(proId));
                        }
                        aqbBankcardService.modifyBankMoney(userId,aqbBankcard.getMoney() - payMoney);
                    }
                    if(aqbBorrowOne.getObligation() == 0){
                        aqbProjectService.modifyStatus(4,Integer.parseInt(proId));

                    }
                }else{
                    model.addAttribute("Msg", "还款金额大于所欠金额，请重新输入");
                    model.addAttribute("proId", proId);
                    return "redirect:/borrow/info";
                }
            }
        } else {
            model.addAttribute("Msg", "卡内余额不足");
            model.addAttribute("proId", proId);
            return "redirect:/borrow/info";
        }
        model.addAttribute("proId", proId);
        return "redirect:/borrow/info";
    }

    @RequestMapping(value = "/isTrue", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String isTrue(String pwd, HttpSession session) {
        String userId = ((AqbUser) session.getAttribute(Constants.USER_SESSION)).getUserId().toString();
        AqbBankcard aqbBankcard = aqbBankcardService.findByUserId(userId);
        StringBuffer sb = new StringBuffer("{");
        sb.append("\"isPass\":");
        if (aqbBankcard.getPassword().equals(pwd)) {
            sb.append("\"pass\"}");
        } else {
            sb.append("\"noPass\",\"Msg\":\"密码不正确\"}");
        }
        return sb.toString();
    }

    public boolean isEnough(double payMoney, String userId) {
        boolean isPass = false;
        //判断账户所剩余金额是否足够支付输入金额
        AqbBankcard aqbBankcard = aqbBankcardService.findByUserId(userId);
        if (aqbBankcard.getMoney() >= payMoney) {
            isPass = true;
        }
        return isPass;
    }
}
